<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Iphone, Message, User } from "@element-plus/icons-vue";

const route = useRoute();
const productId = route.params.id;

const car = ref(null);
const getCarById = async () => {
  try {
    const response = await axios.get(`/car/getCarById`, { params: { id: productId } });
    car.value = response.data;
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const loginForm = reactive({
  name: '',
  productId: productId,
  telephone: '',
  code: '',
  appointmentDate: '',
  sex: '1',
});
const refSmsForm = ref(null);
const rulesLoginForm = reactive({
  appointmentDate: [
    { required: true, message: '请选择预约时间', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度必须是4位', trigger: 'blur' }
  ]
});
const smsDisabled = ref(false);
const smsText = ref('发送短信验证码');
const sendSms = () => {
    smsDisabled.value = true;
    axios.get(`/users/sendSms/${loginForm.telephone}`).then(resp => {
      ElMessage.success(resp.data);
    }).catch(error => {
      ElMessage.error(error.response.data);
    }).finally(() => {
      let seconds = 15;
      smsText.value = `${seconds}秒后重新发送`;
      const timer = setInterval(() => {
        seconds--;
        if (seconds > 0) {
          smsText.value = `${seconds}秒后重新发送`;
        } else {
          smsText.value = "发送短信验证码";
          smsDisabled.value = false;
          clearInterval(timer);
        }
      }, 1000);
    });
};

const isSubmitDisabled = ref(false);
const submit = () => {
  refSmsForm.value.validate(valid => {
    if (valid) {
      axios.post('/appointments/submit', loginForm).then(resp => {
        ElMessage.success("预约成功！稍后会给你发送短信通知")
        isSubmitDisabled.value = true;
        setTimeout(() => {
          axios.post('/appointments/sendSms',loginForm).then(resp => {
            alert(resp.data);
            window.location.href = "/";
          })
        }, 5000);

      }).catch(error => {
        ElMessage.error(error.response.data);
      });
    } else {
      ElMessage.error("请填写完整的表单信息！");
    }
  });
};

onMounted(() => {
  getCarById();
});
</script>

<template>
  <div class="reservation-container">
    <div class="car-details">
      <div class="car-text">
        <h2>到店试驾</h2>
        <p>店端精选试驾路线，在线预约试驾心仪车型</p>
      </div>

      <div class="car-image">
        <img v-if="car" :src="$urlImage + car.imgs" alt="车辆图片"/>
        <p>*我们将尽力满足您意向时间和意向车型的选择，实际试驾时间和车型将由经销商与您最终确认。更多详情请致刘炳楠先生的电话：13339819839。</p>
      </div>
    </div>


    <div class="form-container">
      <div v-if="car" class="car-info">
        <p>预约试驾</p>
        <h3>{{ car.name }}</h3>
        <p>价格: ¥{{ car.price }}起</p>
        <p>油耗: {{ car.fuelConsumption }} L/100km</p>
        <p>最高速度: {{ car.maxSpeed }} km/h</p>
        <p>座位数: {{ car.seatCount }} 座</p>
      </div>

      <el-form ref="refSmsForm" :model="loginForm" :rules="rulesLoginForm" class="reservation-form" label-position="left">

        <el-form-item label="姓名：" prop="name">
          <el-input v-model="loginForm.name" placeholder="请输入姓名(选填)"></el-input>
        </el-form-item>

        <el-form-item label="性别：" prop="sex">
          <el-radio-group v-model="loginForm.sex">
            <el-radio label="男" value="1">先生</el-radio>
            <el-radio label="女" value="0">女士</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="预约时间：" prop="appointmentDate">
          <el-date-picker
              v-model="loginForm.appointmentDate"
              type="datetime"
              placeholder="请选择预约时间"
              :shortcuts="[
      { text: '今天', onClick(picker) { picker.$emit('pick', new Date()); } },
      { text: '明天', onClick(picker) { picker.$emit('pick', new Date(new Date().getTime() + 24 * 60 * 60 * 1000)); } }]"/>
        </el-form-item>


        <el-form-item label="手机号：" prop="telephone">
          <el-input v-model="loginForm.telephone" placeholder="请输入手机号">
            <template #suffix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码：" prop="code">
          <div class="form-item-container">
            <el-input v-model="loginForm.code" maxlength="4" minlength="4" placeholder="验证码" style="width: 90px; margin-right: 10px;"></el-input>
            <el-button type="text" :disabled="smsDisabled" @click="sendSms">
              <el-icon :size="20"><Message /></el-icon>{{ smsText }}
            </el-button>
          </div>
        </el-form-item>

        <div class="login-btn-container">
          <el-button style="width: 150px;" type="primary" :disabled="isSubmitDisabled"  @click="submit">
            <el-icon><User /></el-icon>提交预约订单
          </el-button>
        </div>

      </el-form>
    </div>
  </div>
</template>

<style scoped>
.reservation-container {
  display: flex;
  justify-content: space-between;
  margin: 20px 10%;
  background: rgba(255, 255, 255, 0.76);
  padding: 20px;
  border-radius: 8px;
}

.car-details {
  display: flex;
  flex-direction: column;
  width: 60%;
}

.car-text {
  margin-bottom: 10px;
}

.car-text h3 {
  font-size: 24px;
  margin-bottom: 5px;
}

.car-text p {
  font-size: 18px;
}

.car-image img {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.form-container {
  width: 40%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.submit-btn:disabled {
  background-color: #dcdfe6;
}
</style>
